import { login, logout, getUserInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {
      account: '',
      avatar: '',
      nickName: '',
      password: '',
      phone: '',
      realName: '',
      sex: ''
    }
  }
}
const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
// 登陆
  login({ commit }, userInfo) {
    //
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password }).then(res => {
        const data = res.data
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getUserInfo({ commit }, state) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        const { data } = res
        if (!data) {
          return reject('请重新登陆')
        }
        commit('SET_USERINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
        console.log(121)
        if (res.code === '201') {
          this.$message.error('请重新登录')
          removeToken()
          this.$router.push('/login')
        } else {
          removeToken()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        }
      }).catch(error => {
        if (error) {
          removeToken()
          location.reload()
          this.$router.push('/login')
        }
        reject(error)
      })
    })
  },
  // removeToken
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

